// Launcher of the ZorLog compatible binary logger

#include <nuttx/config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/prctl.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <poll.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <visibility.h>
#include <systemlib/err.h>
#include <systemlib/systemlib.h>
#include <drivers/drv_hrt.h>
#include <common/thread.h>
#include "logger.h"

static Runnable *runnable_ = NULL;

extern "C" __EXPORT int sdzorlog_main(int argc, char *argv[]);
extern "C" __EXPORT int sdzorlog_thread_main(int argc, char *argv[]);

extern "C" int sdzorlog_thread_main(int argc, char *argv[])  {
	runnable_ = new Logger();
	runnable_->run_();
	delete runnable_;
	runnable_ = NULL;
	return 0;
}

static void sdzorlog_usage(const char *reason) {
	if (reason)
		fprintf(stderr, "%s\n", reason);

	errx(1, "usage: sdzorlog {start|stop|status} [-r <log rate in Hz>]\n");
}

/**
 * The logger deamon app only briefly exists to start the background job.
 * The stack size assigned in the Makefile does only apply to this management task.
 * The actual stack size should be set in the call to task_spawn().
 */
extern "C" __EXPORT int sdzorlog_main(int argc, char *argv[]) {
	if (argc < 2)
		sdzorlog_usage("missing command");

	if (!strcmp(argv[1], "start")) {
		if (runnable_ != NULL) {
			printf("sdzorlog already running\n");
			exit(1);
		}

		task_spawn_cmd("sdzorlog", SCHED_DEFAULT, SCHED_PRIORITY_DEFAULT, 2048,
				sdzorlog_thread_main, (const char **)argv);

		exit(0);
	}

	if (!strcmp(argv[1], "stop")) {
		if (runnable_ != NULL)
			runnable_->setExitFlag();
		exit(0);
	}

	else if (!strcmp(argv[1], "status")) {
		printf("sdzorlog is %s\n", (runnable_ != NULL) ? "running" : "not started");
		exit(0);
	}

	sdzorlog_usage("unrecognized command");
	exit(1);
}
